package com.example.facility.common;

import lombok.EqualsAndHashCode;
import lombok.Getter;

/**
 * 带错误码的异常
 *
 * @author pan
 * @since 2023-06-15
 */
@EqualsAndHashCode(callSuper = true)
public class ErrorCodeException extends RuntimeException {

    /**
     * 全局错误码
     *
     * @see GlobalErrorCodeConstants
     */
    @Getter
    private Integer code;
    /**
     * 错误提示
     */
    private String message;

    /**
     * 负载对象
     */
    private Object payload;

    /**
     * 空构造方法，避免反序列化问题
     */
    public ErrorCodeException() {
    }

    public ErrorCodeException(ErrorCode errorCode) {
        this.code = errorCode.getCode();
        this.message = errorCode.getMsg();
    }

    public ErrorCodeException(ErrorCode errorCode, Object... params) {
        this.code = errorCode.getCode();
        this.message = ServiceExceptionUtil.doFormat(errorCode.getCode(), errorCode.getMsg(), params);
    }

    /**
     * 构造函数
     *
     * @param code 错误码
     */
    public ErrorCodeException(Integer code) {
        super();
        this.code = code;
    }

    /**
     * 构造函数
     *
     * @param code    错误码
     * @param message 错误描述
     */
    public ErrorCodeException(Integer code, String message) {
        this.code = code;
        this.message = message;
    }

    /**
     * 构造函数
     *
     * @param code    错误码
     * @param message 错误描述
     * @param t       原始异常
     */
    public ErrorCodeException(Integer code, String message, Throwable t) {
        super(message, t);
        this.code = code;
    }

    public ErrorCodeException setCode(Integer code) {
        this.code = code;
        return this;
    }

    @Override
    public String getMessage() {
        return message;
    }

    public ErrorCodeException setMessage(String message) {
        this.message = message;
        return this;
    }

    public void setPayload(Object payload) {
        this.payload = payload;
    }
}
